package suxinyi.rbac.util;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 工具类-单例工厂
 *
 * @author 苏心怡
 * @since 2025/6/7 22:22
 */
public class SingletonFactory {

    private static final Map<Class<?>, Object> instanceMap = new ConcurrentHashMap<>();

    public static <T> T getInstance(Class<T> clazz) {
        if (clazz == null) {
            throw new IllegalArgumentException("未知的类型");
        }
        if (!instanceMap.containsKey(clazz)) {
            try {
                Constructor<T> constructor = clazz.getDeclaredConstructor();
                constructor.setAccessible(true);
                T singleton = constructor.newInstance();
                instanceMap.put(clazz, singleton);
            } catch (Exception e) {
                throw new IllegalArgumentException("创建单例模式失败：" + clazz.getSimpleName(), e);
            }
        }
        return (T)instanceMap.get(clazz);
    }
}
